<template>
  <el-row class="filter-list-view" v-if="tabs.length > 0 && Object.keys(formModel).length > 0">
    <el-form ref="form" inline validateOnRuleChange label-width="100px" size="medium">
      <template v-for="tab in tabs" v-if="showFilterTab(tab)">
        <el-form-item :label="tab.label">
          <div v-if="tab._type === 'input'">
            <el-row :gutter="5">
              <el-col :span="24">
                <el-input col="2" :placeholder="tab.placeholder" clearable :name="tab.list_tab_no"
                  v-model="formModel[tab.list_tab_no].value"></el-input>
              </el-col>
              <!-- <el-col :span="6">
                <el-radio-group
                  :disabled="formModel[tab.list_tab_no].value == ''"
                  v-model="inputMoreConfig.value"
                >
                  <el-radio
                    :label="item.value"
                    name="type"
                    v-for="(item, index) in inputMoreConfig.options"
                    :key="index"
                  >
                    {{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-col> -->
            </el-row>
          </div>
          <div v-if="tab._type === 'between'">
            <el-col :span="11">
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" startPlaceholder="开始日期" endPlaceholder="结束日期"
                type="datetimerange" appendToBody placeholder="选择日期" v-model="formModel[tab.list_tab_no].value"
                style="width: 100%"></el-date-picker>
              <!-- <el-date-picker startPlaceholder="开始日期" endPlaceholder="结束日期" type="datetimerange" appendToBody placeholder="选择日期" v-model="form.date1" style="width: 100%;"></el-date-picker> -->
            </el-col>
            <!-- <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-time-picker
                placeholder="选择时间"
                v-model="form.date2"
                style="width: 100%"
              ></el-time-picker>
            </el-col> -->
          </div>
          <div v-if="tab._type === 'select'">
            <selectPlus :main-data="mainData" :ref="tab.list_tab_no" :tab="tab" :formModels="formModel"
              :formModel="formModel[tab.list_tab_no]" @on-value-change="selectChange($event, tab)"></selectPlus>
            <!-- <el-select
              filterable
              remote
              :loading="loading"
              v-model="formModel[tab.list_tab_no].value"
              clearable
              placeholder="输入关键字搜索"
              :remote-method="buildFkOptionList"
              @blur="buildFkOptionList(null, tab)"
            >
              <el-option
                v-for="item in formModel[tab.list_tab_no].options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select> -->
          </div>
          <div v-if="tab._type === 'checkbox'">
            <el-checkbox-group v-model="formModel[tab.list_tab_no].value" v-if="tab._colSrvData">
              <el-checkbox :label="item.value" :name="item.value" v-for="(item, index) in tab.options" :key="index"
                @change="onCheckChange($event, item, tab.list_tab_no)">
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-if="tab._type === 'radio'">
            <el-radio-group v-model="formModel[tab.list_tab_no].value" v-if="tab._colSrvData"
              v-show="tab.options && tab.options.length > 0">
              <el-radio :label="item.value" name="type" v-for="(item, index) in tab.options" :key="index">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </div>
          <div v-else-if="tab._type === 'img'">
            <el-row :gutter="5">
              <el-col :span="24">
                <upload-image :field="buildImgField(tab)" :limit="1" @change="tabChange($event, tab)">
                </upload-image>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
      </template>

      <!-- <el-form-item>
            <el-button type="primary" @click="buildConditions(formModel)">查询</el-button>
            <el-button>重置</el-button>
        </el-form-item> -->
    </el-form>
  </el-row>
</template>
<script>
import cloneDeep from "lodash/cloneDeep";
import * as DataUtil from "../../util/DataUtil";
import selectPlus from "../ui/select-plus.vue";
import UploadImage from "../ui/upload-image.vue";
import { onFetch } from "../../common/httpUtil";
export default {
  name: "filter-tabs",
  data() {
    return {
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      loading: false,
      inputMoreConfig: {
        value: "",
        options: [
          {
            label: "匹配开始",
            value: "like]",
          },
          {
            label: "匹配尾部",
            value: "[like",
          },
        ],
      },
      formModel: {},
      onInputValue: false, // 是否有输入值
    };
  },
  components: { UploadImage, selectPlus },
  props: {
    tabs: {
      type: Array,
      default: function () {
        return [];
      },
    },
    cols: {
      type: Array,
      default: function () {
        return [];
      },
    },
    srv: {
      type: String,
      default: function () {
        return "";
      },
    },
    mainData: Object,
    defaultCondition: Array,
    $srvApp: String,
  },
  computed: {
    tabRun: function () {
      let self = this;
      let tabs = self.tabs;
      return tabs;
    },
  },
  created() {
    let self = this;
    self.onBuildFormValues();
  },
  mounted() { },
  methods: {
    refreshRelatedTabOptions() {
      // 刷新关联tab的options
      if (this.tabs?.length) {
        this.tabs.forEach((tab) => {
          if (tab?.inputType === "group") {
            let options = [];
            this.$set(tab, "options", options);
            if (tab?.option_list?.length && !tab?.options?.length) {
              tab.options = tab.option_list
              this.$set(this.formModel[tab.list_tab_no], "options", tab.option_list);
              return
            }
            this.buildGroupTags(tab).then((res) => {
              let opts = res;
              for (let cs = 0; cs < opts.length; cs++) {
                let obj = {
                  label: "",
                  value: "",
                };
                obj.label = opts[cs].tagName;
                obj.value = opts[cs].value;
                obj.ruleType = opts[cs].ruleType;
                obj.checked =
                  opts[cs].default === undefined ? false : opts[cs].default;
                options.push(obj);
              }
              this.$set(this.formModel[tab.list_tab_no], "options", options);
            });
          }
        });
      }
    },
    showFilterTab(tab) {
      if (["checkbox", "radio"].includes(tab._type)) {
        return tab?.options?.length > 0 || this.formModel[tab.list_tab_no]?.options?.length;
      } else {
        return true;
      }
    },
    tabChange(no, tab) {
      this.$set(this.formModel[tab.list_tab_no], "value", no);
    },
    buildImgField(item) {
      let _colSrvData = {};
      if (item?._colSrvData?.length) {
        _colSrvData = item._colSrvData[0];
        if (
          _colSrvData?.more_config &&
          typeof _colSrvData?.more_config === "string"
        ) {
          try {
            _colSrvData._moreConfig = JSON.parse(_colSrvData.more_config);
          } catch (e) { }
        }
      }
      return {
        getAnyValidateError: () => {
          return "";
        },
        info: {
          editable: true,
          moreConfig: {
            fileMaxSize: _colSrvData._moreConfig?.fileMaxSize
              ? _colSrvData._moreConfig?.fileMaxSize * 1024
              : item.more_config?.fileSize, //MB
          },
          srvCol: {
            columns: item.more_config?.colName,
            table_name: item.table_name,
          },
        },
        fileDesc: item.more_config?.fileDesc || null, //底部提示
        fileType:
          _colSrvData?._moreConfig?.fileType || item.more_config?.fileType, // 默认jpg/png/svg
        fileSize: _colSrvData._moreConfig?.fileMaxSize
          ? _colSrvData._moreConfig?.fileMaxSize * 1024
          : item.more_config?.fileSize, // 默认2MB
        model: item.default,
      };
    },
    selectChange(e, tab) {
      console.log(e, tab);
      this.$set(this.formModel[e.listNo], "value", e.value);
    },
    onBuildFormValues() {
      let self = this;
      let tabs = this.tabs;
      let model = {};
      tabs.forEach((item, index) => {
        let col = {
          colName: item._colName,
          value: "",
          inputType: item.inputType,
          formType: "",
          default: item.default,
        };
        //   if(item.inputType = 'fk'){
        //       item.options = []
        //        item.buildoptions = self.getTabOptions(item)
        //   }else{
        //       item.options = self.getTabOptions(item)
        //   }
        item.options = self.getTabOptions(item);

        // this.$set(item,'options',self.getTabOptions(item))
        //console.log(item.inputType,item.options)
        col.colName = item._colName;
        col.inputType = item.inputType;
        col.formType = item._type;
        col.tags = item.more_config.tags || [];
        col.options = [];
        if (item.inputType == "group") {
          col.tags = item.options;
        }
        if (item._type === "checkbox" || item._type === "radio") {
          if (item._type === "radio") {
            col.value = item.default == "" ? "" : item.default;
          } else {
            col.value = item.default == "" ? [] : item.default.split(",");
          }

          if (item.showAllTag && col.value.length == 0) {
            col.value?.unshift?.("_unlimited_");
          }

          model[item.list_tab_no] = col;
        } else if (item._type === "input") {
          col.value = item.default;
          model[item.list_tab_no] = col;
        } else if (item._type === "select" && item.inputType == "fk") {
          col.value = "";
          col.options = item["_options"];
          model[item.list_tab_no] = col;
        } else if (item._type === "img") {
          col.value = item.default || "";
          model[item.list_tab_no] = col;
        } else if (item._type === "between") {
          col.value = item.default || [];
          model[item.list_tab_no] = col;
        }
      });
      self.formModel = model;
    },
    getTabSrvCol(tab) {
      let col = tab._colName;
      //   tab._colName = col.split(',')
      let cols = tab._colName;
      let srvCols = this.cols;
      for (let key in cols) {
        for (let c in srvCols) {
          if (cols[key] === srvCols[c].columns) {
            return srvCols[c];
          }
        }
      }
    },
    onChange(e, t) {
      //console.log(e)
    },
    getChecked(e, val) {
      let checked = false;
      let checkedItem = e.join(",");
      if (checkedItem.indexOf("_unlimited_") !== -1 && val === "_unlimited_") {
        return true;
      } else {
        return false;
      }
    },
    onCheckChange(e, item, tabno) {
      //   this.formModel[n].value =
      // 初始不限选项的选中切换
      let self = this;

      if (e === true && item.value === "_unlimited_") {
        self.formModel[tabno].value = ["_unlimited_"];
      } else if (e === true && item.value !== "_unlimited_") {
        let val = self.formModel[tabno].value;
        self.formModel[tabno].value = val.filter((citem, index) => {
          if (citem !== "_unlimited_") {
            return citem;
          }
        });
      }
      // console.log('e',e)
    },
    onReset() {
      this.onBuildFormValues();
    },
    getTabOptions(tab) {
      let self = this;
      if (tab.hasOwnProperty("_colSrvData")) {
        let scol = tab._colSrvData;
        let col = tab._colName;
        let options = [];
        if (
          tab._type === "select" ||
          tab._type === "checkbox" ||
          tab._type === "radio"
        ) {
          if (
            tab.inputType === "Enum" ||
            tab.inputType === "Dict" ||
            tab.inputType === "fk"
          ) {
            options = [];
            tab["value"] = [];
            for (let c = 0; c < col.length; c++) {
              for (let cs = 0; cs < scol.length; cs++) {
                if (
                  col[c] === scol[cs].columns &&
                  scol[cs].col_type === "Enum"
                ) {
                  options = scol[cs].option_list_v2;
                  if (tab.showAllTag && options !== undefined) {
                    options.unshift({
                      label: "不限",
                      value: "_unlimited_",
                    });
                  }
                  return options;
                } else if (
                  col[c] === scol[cs].columns &&
                  scol[cs].col_type === "Dict"
                ) {
                  options = scol[cs].option_list_v2;
                  if (tab.showAllTag && options !== undefined) {
                    options.unshift({
                      label: "不限",
                      value: "_unlimited_",
                    });
                  }
                  return options;
                }
                if (
                  (col[c] === scol[cs].columns && scol[cs].col_type === "fk") ||
                  scol[cs].col_type === "Fk"
                ) {
                  options = tab["_options"];
                  console.log("getTabOptions", tab);
                  return options;
                }
              }
            }
          } else if (
            ["String"].includes(tab.inputType) &&
            !tab.more_config.tags &&
            ["checkbox", "radio"].includes(tab.more_config.type)
          ) {
            console.log(tab, "getTabOptions");
            tab.option_list = {
              serviceName: tab.service,
              refed_col: tab.more_config.colName,
              key_disp_col: tab.more_config.colName,
              group: [{}],
            };
            return [];
          } else if (
            tab.inputType === "BetweenDate" ||
            tab.inputType === "BetweenNumber" ||
            tab.inputType === "Date" ||
            tab.inputType === "DateTime" ||
            tab.inputType === "String"
          ) {
            tab["value"] = [];
            options = [];
            let opts = tab.more_config.tags;
            for (let cs = 0; cs < opts.length; cs++) {
              let obj = {
                label: "",
                value: "",
              };
              obj.label = opts[cs].tagName;
              obj.value = opts[cs].value;
              obj.ruleType = opts[cs].ruleType;
              obj.checked =
                opts[cs].default === undefined ? false : opts[cs].default;
              options.push(obj);
            }
            if (tab.showAllTag && options !== undefined) {
              options.unshift({
                label: "不限",
                value: "_unlimited_",
              });
            }
            return options;
          } else if (tab.inputType === "group") {
            let options = [];
            // self.buildGroupTags(tab).then((res) => {
            //   let opts = res;
            //   for (let cs = 0; cs < opts.length; cs++) {
            //     let obj = {
            //       label: "",
            //       value: "",
            //     };
            //     obj.label = opts[cs].tagName;
            //     obj.value = opts[cs].value;
            //     obj.ruleType = opts[cs].ruleType;
            //     obj.checked =
            //       opts[cs].default === undefined ? false : opts[cs].default;
            //     options.push(obj);
            //   }
            // });
            // self.$set(tab, "options", options);
            return options;
          }
        }
      } else {
        return [];
      }
    },

    async buildGroupTags(e) {
      let colName = e._colName[0] || "";

      let group = [
        {
          colName: colName,
          type: "by",
        },
      ];
      let condition = [];
      if (
        Array.isArray(this.defaultCondition) &&
        this.defaultCondition.length
      ) {
        condition = cloneDeep(this.defaultCondition);
      }

      let options = [];
      // service_name, condition, page, order, group, mapcondition, app, isproc, columns, relationCondition, draft, pageType, srvAuth,vpageNo,useType,rdt,divCondition
      //   const res = await this.select(
      //     this.srv,
      //     condition,
      //     null,
      //     null,
      //     group,
      //     null
      //   );
      //   const resData = res.data.data;

      const res = await onFetch(
        {
          app: this.$srvApp,
          service: this.srv,
          condition: condition,
          group: group,
          page: {
            pageNo: 1,
            rownumber: 100,
          },
        },
        this
      );
      if (res.state === "SUCCESS") {
        const resData = res.data;
        for (let i = 0; i < resData.length; i++) {
          const item = resData[i];
          const opt = {
            ruleType: "eq",
            tagName: item[colName],
            value: item[colName],
          };
          if (item[colName]) {
            options.push(opt);
          }
        }
        return options;
      } else if (res.resultMessage) {
        this.$message.error(res.resultMessage);
        return [];
      }
    },
    buildConditions(e) {
      let self = this;
      let condsModel = self.formModel;
      let relation_Conditions = {
        relation: "AND",
        data: [],
      };
      let tabs = Object.keys(condsModel);

      let colData = {};
      let relation = {
        relation: "OR",
        data: [],
      };
      for (let i = 0; i < tabs.length; i++) {
        relation.data = [];
        let child_relation = {
          relation: "AND",
          data: [],
        };
        colData = {
          colName: "",
          ruleType: "",
          value: "",
        };
        const { formType, inputType, value, colName } =
          condsModel[tabs[i]] || {};
        if (
          ["checkbox", "radio"].includes(formType) &&
          value?.length &&
          value[0] !== "_unlimited_"
        ) {
          if (["BetweenNumber", "Date", "DateTime"].includes(inputType)) {
            relation.relation = "AND";
            relation.data = [];
            let values = ["Date", "DateTime"].includes(inputType)
              ? self.formatDateValues(value)
              : value;
            const valuesLength = values?.length||0
            for (let v = 0; v < valuesLength; v++) {
              child_relation = {
                relation: "AND",
                data: [],
              };

              let betval = values[v].split(",");
              for (let j = 0; j < betval.length; j++) {
                colData = {
                  colName: "",
                  ruleType: "",
                  value: "",
                };
                if (betval[j] !== "-") {
                  if (j === 0 && betval[j] !== "-") {
                    colData.colName = colName[0];
                    colData.value = ["Date", "DateTime"].includes(inputType)
                      ? betval[j]
                      : Number(betval[j]);
                    colData.ruleType = betval.length > 1 ? "ge" : "like"; // 只有一个只时候 按照 like 查询
                  } else if (betval[j] !== "-") {
                    colData.colName = colName[0];
                    colData.value = ["Date", "DateTime"].includes(inputType)
                      ? betval[j]
                      : Number(betval[j]);
                    colData.ruleType = "le";
                  }
                  if (values.length > 1) {
                    child_relation.data.push(cloneDeep(colData));
                  } else {
                    relation.data.push(cloneDeep(colData));
                  }
                }
              }

              if (values.length > 1) {
                relation.relation = "OR"; // 大于1个选项时处理 OR
                relation.data.push(cloneDeep(child_relation));
              }
            }
          } else if (["Group", "group", "Dict", "Enum"].includes(inputType)) {
            relation.relation = "OR";
            colData.colName = colName[0];
            colData.value = formType == "radio" ? value : value.join(",");
            colData.ruleType = "in";
            relation.data.push(cloneDeep(colData));
          } else if (condsModel[tabs[i]].inputType === "String") {
            let tags = condsModel[tabs[i]].tags;
            // let rt =
            let val = condsModel[tabs[i]].value;
            for (let j = 0; j < val.length; j++) {
              let rt = tags.filter((item) => {
                if (item.value === val[j]) {
                  return item;
                }
              });
              if (rt?.length) {
                relation.relation = "OR";
                colData.colName = condsModel[tabs[i]].colName[0];
                colData.value = val[j];
                colData.ruleType = rt[0].ruleType;
                relation.data.push(cloneDeep(colData));
              }
            }
          }
        } else if (inputType === "BetweenDate" && value?.length) {
          relation.data.push({
            colName: colName[0],
            ruleType: "between",
            value: value,
          });
        } else if (formType === "input" && value.length !== 0) {
          child_relation = {
            relation: "OR",
            data: [],
          };
          for (let col = 0; col < colName.length; col++) {
            colData.colName = colName[col];
            colData.value = value;
            if (self.inputMoreConfig.value !== "") {
              colData.ruleType = self.inputMoreConfig.value;
            } else {
              colData.ruleType = "[like]";
            }
            relation.data.push(cloneDeep(colData));
          }
        } else if (inputType == "fk") {
          relation.relation = "OR";
          colData.colName = colName[0];
          colData.value = formType == "select" ? value : value.join(",");
          colData.ruleType = "eq";
          if (value != "" && value != null) {
            relation.data.push(cloneDeep(colData));
          }
        } else if (formType === "img" && value.length !== 0) {
          child_relation = {
            relation: "OR",
            data: [],
          };
          for (let col = 0; col < colName.length; col++) {
            colData.colName = colName[col];
            colData.value = value;
            if (self.inputMoreConfig.value !== "") {
              colData.ruleType = self.inputMoreConfig.value;
            } else {
              colData.ruleType = "eq";
            }
            relation.data.push(cloneDeep(colData));
          }
        }
        if (relation.data.length !== 0) {
          relation_Conditions.data.push(cloneDeep(relation));
        }
      }
      return relation_Conditions;
    },
    formatDateValues(e) {
      let exps = e;
      let typeConfig = ["nowDay", "nowWeek", "nowMonth", "nowYear"];
      let type = null; // nowDay | nowWeek | nowMonth | nowYear
      let increment = 0;
      for (let key in typeConfig) {
        if (exps.indexOf(typeConfig[key]) !== -1) {
          type = typeConfig[key];
        }
      }
      let startAndEnd = exps.indexOf(",") !== -1 ? exps.split(",") : [exps];
      if (startAndEnd[0] == type) {
        increment = startAndEnd.length == 1 ? 0 : startAndEnd[1];
      } else {
        increment = -startAndEnd[0];
      }
      if (type === "nowWeek") {
        return DataUtil.getWeekStartAndEnd(increment);
      } else if (type === "nowDay") {
        return DataUtil.getDayStartAndEnd(increment);
      } else if (type === "nowMonth") {
        return DataUtil.getMonthStartAndEnd(increment);
      } else if (type === "nowYear") {
        return dataUtil.getYearStartAndEnd(increment);
      }
    },
  },
  watch: {
    formModel: {
      deep: true,
      immediate: true,
      handler: function (val, oldVal) {
        let keys = Object.keys(val);
        let onNew = false;
        let newNum = 0;
        this.$emit("on-input-value", true);
        this.$emit("on-change", true);
        console.log("更新了", cloneDeep(val),cloneDeep(oldVal));
        for (let i = 0; i < keys.length; i++) {
          //   console.log("更新了",val[keys[i]].value, oldVal[keys[i]].value)
          if (
            val[keys[i]] &&
            oldVal[keys[i]] &&
            val[keys[i]].hasOwnProperty("value") &&
            oldVal[keys[i]].hasOwnProperty("value") &&
            val[keys[i]].value !== oldVal[keys[i]].value
          ) {
            newNum++;
            this.$emit("on-input-value", true);
            this.$emit("on-change", true);
            console.log("更新了");
          } else if (
            val[keys[i]] &&
            oldVal[keys[i]] &&
            val[keys[i]].hasOwnProperty("value") &&
            !oldVal[keys[i]].hasOwnProperty("value") &&
            val[keys[i]].value !== oldVal[keys[i]].value
          ) {
            this.$emit("on-input-value", true);
            this.$emit("on-change", true);
            console.log("更新了");
          }
        }
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.filter-list-view {
  border: 1px solid #f2f2f2;
  padding: 5px;
}

.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 8px;
}
</style>